///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.browser {
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	
	import sugarcookie.validators.EmailValidator;
	
	import mx.logging.Log;
	import mx.logging.ILogger;
	
	/**
	 * Formats an href call to 'mailto' to setup an email within the users email client.
	 */
	public class MailTo {
		//--------------------------------------------------------------------------
	    //
	    //  Class properties
	    //
	    //--------------------------------------------------------------------------
		
		/**
		 * @private
		 */
		private static var _log:ILogger = Log.getLogger("sugarcookie.browser.MailTo");;
		
		//--------------------------------------------------------------------------
	    //
	    //  Class methods
	    //
	    //--------------------------------------------------------------------------
		
		/**
		 * Constructs the mailTo call and executes
		 *
		 * @param recipient Can be a single recipient or and array of recipients.  no spaces in comma delineated list.
		 * @param props Optional array with additional properites to format the email such as subject, cc, bcc and body.
		 */
		public static function sendMail(recipient:String, props:Object=null):Boolean {
			if (recipient.indexOf(" ")>=0) return false;
			
			if (recipient.indexOf(",")>=0) {
				var recipientlist:Array = recipient.split(",");
				for (var i:Number=0;i<recipientlist.length;i++) {
					if (!EmailValidator.validate(recipientlist[i])) return false;
				}
			} else {
				if (!EmailValidator.validate(recipient)) return false;
			}
			
			var status:Boolean = true;
			var callStr:String = "mailto:"+recipient;
			_log.debug("props: "+props);
			if (props!=null) {
				callStr += "?"
				for (var n:String in props) {
					if (props[n]!="") {
						callStr += n + "=" + props[n] + "&";
						if (n=="cc" || n=="bcc") {
							if (props[n].indexOf(",")>=0) {
								var proplist:Array = props[n].split(",");
								for (var x:Number=0;x<proplist.length;x++) {
									if (!EmailValidator.validate(proplist[x])) return false;
								}
							}
						}
					}
				}
				if (callStr.charAt(callStr.length - 1)=="&" || callStr.charAt(callStr.length - 1)=="?") callStr = callStr.slice(0,-1);
			}
			_log.debug("callStr: "+callStr);
			navigateToURL(new URLRequest(callStr));
			
			return status;
		}
	}
}